package com.hero.herocat;

import com.hero.herocat.handler.IHandler;
import com.hero.herocat.handler.ServletHandler;
import com.hero.herocat.handler.StaticResourceHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;

import java.util.ArrayList;
import java.util.List;

/**
 * @author linhui
 */
public class CustomServer {
    List<IHandler> handlers = new ArrayList<>();

    ServerResource serverResource = new ServerResource();

    public void start() throws Exception {
        init();
        runServer();
    }

    private void init() {
        /// 初始化处理类
        StaticResourceHandler staticResourceHandler = new StaticResourceHandler();
        handlers.add(staticResourceHandler);

        ServletHandler servletHandler = new ServletHandler();
        servletHandler.init(serverResource);
        handlers.add(servletHandler);

    }

    private void runServer() throws Exception {

        EventLoopGroup parent = new NioEventLoopGroup();
        EventLoopGroup child = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(parent, child)
                    // 指定存放请求的队列的长度
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    // 指定是否启用心跳机制来检测长连接的存活性，即客户端的存活性
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast("aggregator", new HttpObjectAggregator(512 * 1024));
                            pipeline.addLast(new ServerHandler(handlers));
                        }
                    });
            int port = serverResource.getInt("port", 8080);
            ChannelFuture future = bootstrap.bind(port).sync();
            System.out.println("HeroCat启动成功：监听端口号为:" + port);
            future.channel().closeFuture().sync();
        } finally {
            parent.shutdownGracefully();
            child.shutdownGracefully();
        }
    }
}
